package cn.tedu.tvrd.controller;

import cn.tedu.tvrd.entity.User;
import cn.tedu.tvrd.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/login")
    public int login(User user, String rem,
                     HttpServletResponse response, HttpSession session){
        System.out.println("user = " + user + ", rem = " + rem);
        //通过用户输入的用户名查询出数据库中对应的数据
        User u = mapper.selectByUserName(user.getUsername());
        if (u!=null){//用户存在
            if (u.getPassword().equals(user.getPassword())){
                //记住登录状态
                session.setAttribute("user",u);

                if (rem!=null){//需要记住用户名和密码
                    //创建Cookie对象
                    Cookie c1 = new Cookie("username",user.getUsername());
                    Cookie c2 = new Cookie("password",user.getPassword());
                    //设置保存时间 单位秒
                    c1.setMaxAge(60*60*24*30);
                    //通过response对象将Cookie下发给客户端
                    response.addCookie(c1);
                    response.addCookie(c2);
                }

                return 1;//登录成功
            }
            return 2; //密码错误
        }
        return 3;//用户不存在
    }

    @RequestMapping("/checklogin")
    public boolean check(HttpSession session){
        //取出登录成功时保存进Session里面的user对象
        User user = (User) session.getAttribute("user");
        //有值说明登录过 返回true 反之false
        return user==null?false:true;
    }

    @RequestMapping("/currentuser")
    public User currentUser(HttpSession session){
        //取出登录成功时保存进Session里面的user对象
        User user = (User) session.getAttribute("user");
        //如果user是null 客户端接收到的是""空字符串
        return user;
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        //从Session中删除保存的user对象
        session.removeAttribute("user");
    }
}
